<template>
  <div class="role-form">
    <a-form
      ref="formRef"
      :model="form"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
      label-align="right"
    >
      <a-form-item
        field="roleName"
        label="角色名称"
        :rules="[{ required: true, message: '请输入角色名称' }]"
      >
        <a-input
          v-model="form.roleName"
          placeholder="请输入角色名称"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="roleKey"
        label="权限字符"
        :rules="[{ required: true, message: '请输入权限字符' }]"
      >
        <a-input
          v-model="form.roleKey"
          placeholder="请输入权限字符"
          allow-clear
        />
      </a-form-item>
      
      <a-form-item
        field="roleSort"
        label="角色排序"
      >
        <a-input-number
          v-model="form.roleSort"
          placeholder="请输入角色排序"
          mode="button"
          :min="0"
          :step="1"
          style="width: 100%"
        />
      </a-form-item>
      
      <a-form-item
        field="status"
        label="状态"
      >
        <a-radio-group v-model="form.status">
          <a-radio :value="RoleStatusEnum.ENABLED">正常</a-radio>
          <a-radio :value="RoleStatusEnum.DISABLED">停用</a-radio>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item
        field="remark"
        label="备注"
      >
        <a-textarea
          v-model="form.remark"
          placeholder="请输入备注"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
      
      <a-divider>菜单权限</a-divider>
      
      <menu-tree v-model:menuIds="form.menuIds" />
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { 
  createRole, 
  updateRole,
  Role,
  RoleStatusEnum,
  DataScopeEnum 
} from '@/api/system/role';
import { getRoleMenuList } from '@/api/system/menu';
import MenuTree from './menu-tree.vue';

// 接收父组件传递的属性
const props = defineProps({
  formData: {
    type: Object as () => Partial<Role>,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

// 表单引用
const formRef = ref();

// 表单数据
const form = reactive<Role>({
  id: 0,
  roleName: '',
  roleKey: '',
  roleSort: 0,
  status: RoleStatusEnum.ENABLED,
  remark: '',
  dataScope: DataScopeEnum.ALL, // 保留dataScope字段，但在UI中隐藏
  menuIds: []
});

// 监听formData变化，更新表单数据
watch(
  () => props.formData,
  async (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      Object.assign(form, newVal);
      
      // 如果是编辑模式，获取角色的菜单权限
      if (props.isEdit && form.id) {
        try {
          const res = await getRoleMenuList(form.id);
          form.menuIds = res.data || [];
        } catch (error) {
          console.error('获取角色菜单权限出错:', error);
          Message.error('获取角色菜单权限失败');
        }
      }
    }
  },
  { immediate: true, deep: true }
);

// 验证表单
const validate = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((errors: any) => {
      if (errors) {
        console.log('表单验证失败:', errors);
        resolve(false);
      } else {
        console.log('表单验证通过');
        resolve(true);
      }
    });
  });
};

// 提交表单
const submit = async () => {
  try {
    const submitData = { ...form };
    
    if (props.isEdit) {
      // 编辑角色
      await updateRole(submitData);
      Message.success('更新角色成功');
    } else {
      // 创建角色
      await createRole(submitData);
      Message.success('创建角色成功');
    }
    return true;
  } catch (error) {
    console.error(props.isEdit ? '更新角色失败:' : '创建角色失败:', error);
    Message.error(props.isEdit ? '更新角色失败' : '创建角色失败');
    return false;
  }
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  Object.assign(form, {
    id: 0,
    roleName: '',
    roleKey: '',
    roleSort: 0,
    status: RoleStatusEnum.ENABLED,
    remark: '',
    dataScope: DataScopeEnum.ALL, // 保留dataScope字段，但在UI中隐藏
    menuIds: []
  });
};

// 暴露方法给父组件
defineExpose({
  validate,
  submit,
  resetForm
});
</script>

<style scoped lang="less">
.role-form {
  padding: 16px 0;
}
</style> 